#include "settingdialog.h"
#include <QSettings>
#include <QMessageBox>
#include <QLabel>

SettingDialog::SettingDialog(QWidget *parent) : QDialog(parent)
{
    setWindowTitle("系统设置");
    setFixedSize(400, 200);

    QVBoxLayout *mainLayout = new QVBoxLayout(this);

    QFormLayout *formLayout = new QFormLayout();

    m_apiKeyEdit = new QLineEdit();
    m_apiKeyEdit->setText(getCurrentApiKey());
    formLayout->addRow("DeepSeek API密钥:", m_apiKeyEdit);

    m_timeoutEdit = new QLineEdit();
    m_timeoutEdit->setText(QString::number(getCurrentTimeout()));
    formLayout->addRow("请求超时时间(秒):", m_timeoutEdit);

    mainLayout->addLayout(formLayout);

    QHBoxLayout *btnLayout = new QHBoxLayout();
    QPushButton *saveBtn = new QPushButton("保存");
    QPushButton *cancelBtn = new QPushButton("取消");

    connect(saveBtn, &QPushButton::clicked, this, &SettingDialog::onSaveClicked);
    connect(cancelBtn, &QPushButton::clicked, this, &SettingDialog::onCancelClicked);

    btnLayout->addWidget(saveBtn);
    btnLayout->addWidget(cancelBtn);

    mainLayout->addLayout(btnLayout);
}

void SettingDialog::onSaveClicked()
{
    QSettings settings("AIConfig.ini", QSettings::IniFormat);

    // 保存API密钥
    settings.setValue("API/api_key", m_apiKeyEdit->text().trimmed());

    // 保存超时时间
    bool ok;
    int timeout = m_timeoutEdit->text().toInt(&ok);
    if (ok && timeout > 0) {
        settings.setValue("API/timeout", timeout);
    } else {
        QMessageBox::warning(this, "输入错误", "请输入有效的超时时间");
        return;
    }

    QMessageBox::information(this, "保存成功", "设置已保存");
    accept();
}

void SettingDialog::onCancelClicked()
{
    reject();
}

QString SettingDialog::getCurrentApiKey()
{
    QSettings settings("AIConfig.ini", QSettings::IniFormat);
    return settings.value("API/api_key", "").toString();
}

int SettingDialog::getCurrentTimeout()
{
    QSettings settings("AIConfig.ini", QSettings::IniFormat);
    return settings.value("API/timeout", 10).toInt();
}